package com.wl.cloud.security.component;

import cn.hutool.core.util.ObjUtil;
import com.wl.cloud.security.bean.IgnoreUrlsProperties;
import com.wl.cloud.security.model.LoginUserDetails;
import com.wl.cloud.security.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author: wanglin
 * @date: 2023-09-12 周二
 * @Version: 1.0
 * @Description: jwt 登录授权过滤器
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private IgnoreUrlsProperties ignoreUrlList;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 不需要保护的资源路径允许访问,这里主要是针对放行接口并携带了token的路径，则直接放行；如：注册接口，带了token；
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String url : ignoreUrlList.getUrls()) {
            if (pathMatcher.match(url, request.getRequestURI())) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        String token = jwtTokenUtil.getToken();

        //存在token
        if (StringUtils.isNotBlank(token)) {
            String username = jwtTokenUtil.getUserName(token);
            if (StringUtils.isBlank(username)) {
                filterChain.doFilter(request, response);
                return;
            }

            //内存中是否存在该登录用户，一般存储在Redis，
            LoginUserDetails loginUser = jwtTokenUtil.getLoginUser(username);
            if (ObjUtil.isNull(loginUser)) {
                filterChain.doFilter(request, response);
                return;
            }
            String userKey = jwtTokenUtil.getUserKey(token);
            //验证token是否和用户token一致;根据toke中的user_key标识验证
            if (!loginUser.getToken().equals(userKey)) {
                filterChain.doFilter(request, response);
                return;
            }

            //token 存在用户名，但未登录
            if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
                //若已经登录，则设置 UsernamePasswordAuthenticationToken 认证对象，后面过滤器链会根据是否验证是否进行判断，重新设置用户对象
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), loginUser.getAuthorities());
                authenticationToken.setDetails(loginUser);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
